package com.abredatos.t37.core

import grails.converters.JSON 

class DataController {
	
	def pollutantDataService

    def index = { }
	
	def inDate = {
		def dataList = pollutantDataService.loadDataInDate(params.date)
		if (!dataList.isEmpty()) {
			render dataList as JSON
		} else {
			render "No data: " + params.date
		}
	}
	
	def last = {
		def dataList = pollutantDataService.loadLastData()
		if (!dataList.isEmpty()) {
			render buildStationData(dataList) as JSON
		} else {
			render "No last data"
		}
	}
	
	def lastDataFromStation = {
		def results = pollutantDataService.loadLastDataOfStation(params.stationId, params.pollutant)
		render results as JSON
	}
	
	
	private buildStationData(dataList) {
		dataList.inject([:]) { stationData, measure ->
			if (stationData[measure.stationId.toString()] == null) {
				stationData[measure.stationId.toString()] = []
			}
			stationData[measure.stationId.toString()].add(measure)
			return stationData
		}
	}
}
